package queue;

import java.util.Iterator;

public class LinkedListCircularQueue<E> implements Queue<E>, Iterable<E> {
    private class Node {
        E val;
        Node next;

        public Node(E val, Node next) {
            this.val = val;
            this.next = next;
        }
    }

    public LinkedListCircularQueue() {
    }

    private Node head = new Node(null, null);
    private Node tail = head;
    private int size = 0;
    private int capacity = Integer.MAX_VALUE;

    {
        tail.next = head;
    }

    public LinkedListCircularQueue(int capacity) {
        this.capacity = capacity;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            Node p = head.next;

            @Override
            public boolean hasNext() {
                return p != head;
            }

            @Override
            public E next() {
                E val = p.val;
                p = p.next;
                return val;
            }
        };
    }

    @Override
    public boolean offer(E value) {
        if (isFull()) {
            return false;
        }
        Node added = new Node(value, head);
        tail.next = added;
        tail = added;
        size++;
        return true;
    }

    @Override
    public E poll() {
        if (isEmpty()) {
            return null;
        }
        Node first = head.next;
        head.next = first.next;
        if (first == tail) { // 如果只有一个元素 记得把尾指针移回head
            tail = head;
        }
        size--;
        return first.val;
    }

    @Override
    public E peek() {
        if (isEmpty()) {
            return null;
        }
        return head.next.val;
    }

    @Override
    public boolean isEmpty() {
        return head == tail;
    }

    @Override
    public boolean isFull() {
        return size == capacity;
    }
}
